package 集合.List集合;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;

/*
    使用List的实现类添加三本图书，并遍历
    按价格排序，从低到高(使用冒泡排序)
 */
public class 练习题1 {
    @SuppressWarnings({"all"})
    public static void main(String[] args) {
        ArrayList <Book> arr =  new ArrayList<>();
        arr.add(new Book("三国演义","罗贯中",120));
        arr.add(new Book("西游记","吴承恩",130));
        arr.add(new Book("水浒传","施耐庵",110));



        sort01(arr, new Comparator<Book>() {
            @Override
            public int compare(Book o1, Book o2) {
                double price = o1.getPrice() - o2.getPrice();
                if(price > 0){
                    return 1;
                }else if(price < 0){
                    return -1;
                }else {
                    return 0;
                }
            }
        });
    }

    public static void sort01(ArrayList<Book> list, Comparator<Book> c){
        for (int i = 0; i < list.size() - 1; i++) {
            for (int j = 0; j < list.size() - 1 - i; j++) {
                if(c.compare(list.get(j), list.get(j + 1)) > 0){
                    Book book1 = list.get(j);
                    Book book2 = list.get(j + 1);
                    //集合交换
                    list.set(j, book2);
                    list.set(j + 1, book1);
                }
            }
        }
        for(Book l: list){
            System.out.println(l);
        }
    }
}

class Book{
    private String  name;
    private String auth;
    private double price;

    public Book(String name, String auth, double price) {
        this.name = name;
        this.auth = auth;
        this.price = price;
    }

    @Override
    public String toString() {
        return "Book{" +
                "name='" + name + '\'' +
                ", auth='" + auth + '\'' +
                ", price=" + price +
                '}';
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAuth() {
        return auth;
    }

    public void setAuth(String auth) {
        this.auth = auth;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }
}
